package org.pliers.ribbon.rule;

import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.netflix.loadbalancer.*;
import org.apache.commons.lang.StringUtils;
import org.pliers.CommonConstant;
import org.pliers.LbIsolationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class CustomIsolationRule extends RoundRobinRule {
    private static final Logger log = LoggerFactory.getLogger(CustomIsolationRule.class);
    private final static String KEY_DEFAULT = "default";
    /**
     * 优先根据版本号取实例
     */
    @Override
    public Server choose(ILoadBalancer lb, Object key) {
        log.info("CustomIsolationRule choose:"+key);
        if (lb == null) {
            return null;
        }
        String version;
        if (key != null && !KEY_DEFAULT.equals(key)) {
            version = key.toString();
        } else {
            version = LbIsolationContextHolder.getVersion();
        }

        List<Server> targetList = null;
        List<Server> upList = lb.getReachableServers();
        if (StringUtils.isNotEmpty(version)) {
            //取指定版本号的实例
            targetList = upList.stream().filter(
                    server -> version.equals(
                            ((NacosServer) server).getMetadata().get(CommonConstant.METADATA_VERSION)
                    )
            ).collect(Collectors.toList());
        }

        if (CollectionUtils.isEmpty(targetList)) {
            log.info("CustomIsolationRule targetList isEmpty");
            //只取无版本号的实例
            targetList = upList.stream().filter(
                    server -> {
                        String metadataVersion = ((NacosServer) server).getMetadata().get(CommonConstant.METADATA_VERSION);
                        return StringUtils.isEmpty(metadataVersion);
                    }
            ).collect(Collectors.toList());
        }

        if (!CollectionUtils.isEmpty(targetList)) {
            log.info("CustomIsolationRule targetList isNotEmpty");
            return getServer(targetList);
        }
        return super.choose(lb, key);
    }

    /**
     * 随机取一个实例
     */
    private Server getServer(List<Server> upList) {
        Random r = new Random(1);
        int nextInt = r.nextInt(upList.size());
        return upList.get(nextInt);
    }
}
